package com.mengxuegu.blog.web.controller;

import com.google.common.base.Preconditions;
import com.mengxuegu.blog.util.base.Result;
import com.mengxuegu.blog.util.tools.RequestUtil;
import com.mengxuegu.blog.web.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@Slf4j
public class AuthController {
    private static  final  String HEADER_TYPE = "Basic ";
    @Autowired
    private ClientDetailsService clientDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthService authService;
    @GetMapping("/user/refreshToken")
    public Result refreshToken(HttpServletRequest request){

        try {
            String refreshToken = request.getParameter("refreshToken");
            Preconditions.checkArgument(StringUtils.isNotEmpty(refreshToken),"令牌不能为空");
            String authorization = request.getHeader("Authorization");
            if(authorization == null || !authorization.startsWith(HEADER_TYPE)){
                throw new UnsupportedOperationException("请求头没有client信息");
            }
            String[] strings = RequestUtil.extractAndDecodeHeader(authorization);
            assert strings.length ==2;
            String clienId = strings[0];
            String clientSecret = strings[1];

            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clienId);
            if(clientDetails == null){
                throw new UnsupportedOperationException("clientDetails对应配置信息不搓澡"+ clienId);
            }
            if(!passwordEncoder.matches(clientSecret,clientDetails.getClientSecret())){
                throw new UnsupportedOperationException("无无效"+ clientSecret);
            }
            return  authService.refreshToken(authorization,refreshToken);
        } catch (Exception e) {
            log.error("refreshToken={}",e.getMessage(),e);
            return Result.error("新令牌生成错误"+e.getMessage());
        }
    }
}
